//
//  TJBuyControntroller.m
//  Teleport
//
//  Created by hc-101 on 2020/6/12.
//  Copyright © 2020 xtjun. All rights reserved.
//我要买 我要卖VC

#import "TJOrderListControntroller.h"
#import "TJBuyHeaderView.h"
#import "TJOrderListCell.h"
#import "TJOrderListScreeningController.h"
#import "TJSelectCoinController.h"
#import "TJBuySellNeedAuthController.h"
#import "TJSelectPayWayController.h"
#import "TJConfirmOrderController.h"
#import "TJInputPasswordControntroller.h"
#import "TJOrderDetailControntroller.h"
#import "TJQuickTradingController.h"

@interface TJOrderListControntroller ()<TJOrderListCellDelegate>

@property (weak, nonatomic) TJBuyHeaderView *headerView;
@property (strong, nonatomic) NSMutableArray *datas;

//1,btc 2,usdt
@property (assign, nonatomic) int coinNo;

@property (assign, nonatomic) int pageIndex;
//价格筛选条件
@property (copy, nonatomic) NSString *money;
//1,微信，2，支付宝，3，银行卡.不传,所有方式
@property (copy, nonatomic) NSString *payType;
/**币子名字 **/
@property (copy, nonatomic) NSString *coinName;
/**法币名字 **/
@property (copy, nonatomic) NSString *coinUnit;
/**法币1,cny 2,eur **/
@property (copy, nonatomic) NSString *moneyType;

@property (strong, nonatomic) NSDictionary *authDict;
@property (strong, nonatomic) NSDictionary *priceDict;
@property (strong, nonatomic) NSDictionary *matchEntrustDict;



@property (assign, nonatomic) int selectType;


@end

static NSString * const orderListCell = @"orderListCell";

@implementation TJOrderListControntroller

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _pageIndex = 1;
    
    _coinName = @"BTC";
    _coinUnit = @"CNY";
    _coinNo = 1;
    _moneyType = @"1";
    self.view.backgroundColor = UIColor.whiteColor;
    
    _selectType = _type.intValue;
    
    NSLog(@"_selectType = %d, _type = %@",_selectType, _type);
    
    weakify(self)
    TJBuyHeaderView *headerView = [[TJBuyHeaderView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 280)];
    //0.买单1.卖单
    headerView.seleteType = _selectType;
    _headerView = headerView;
      /**购买按钮 **/
    [headerView.buyButton addTarget:self action:@selector(didClickBuyButton) forControlEvents:UIControlEventTouchUpInside];
      /** 筛选按钮**/
    [headerView.screeningButton addTarget:self action:@selector(didClickScreeningButton) forControlEvents:UIControlEventTouchUpInside];
    /**订单按钮 **/
    [headerView.orderButton addTarget:self action:@selector(didClickOrderButton) forControlEvents:UIControlEventTouchUpInside];
    /**币子选择按钮 **/
    [headerView.coinNameButton addTarget:self action:@selector(didClickCoinNameButton) forControlEvents:UIControlEventTouchUpInside];
     /**选择器选择回调BTC USDT **/
    [headerView setDidClickCoinNameBlock:^(NSString *coinName, NSInteger index) {
        strongify(self)
        //1, BTC, 2 USDT
//        TJGlobalFunc.globalFunc.OTCMainModel.coinNo = (int)index + 1;
        self.coinName = coinName;
        [self.headerView.coinNameButton setTitle:[NSString stringWithFormat:@"%@/%@", self.coinUnit, self.coinName] forState:UIControlStateNormal];
       // 币子选择按钮
        [self.headerView.coinNameButton setImagePosition:LXMImagePositionRight spacing:3];
        [self setPriceValue];
    }];
    
    /**占位图偏移 **/
    self.verticalOffset = 150;
    
    self.tableView.tableHeaderView = headerView;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.rowHeight = 138;
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView registerClass:TJOrderListCell.self forCellReuseIdentifier:orderListCell];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.offset(0);
    }];
    
//    [TJGlobalFunc.globalFunc.OTCMainModel addObserver:self forKeyPath:@"coinNo" options:NSKeyValueObservingOptionNew context:nil];
    //获取所有币种单价
    [self loadCoinPriceData];
    //获取委托单
    [self loadNewData];

}
//kvo
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    TJLog(@"keyPath = %@, NSKeyValueChangeNewKey = %@",keyPath, change[NSKeyValueChangeNewKey]);
    
    if ([keyPath isEqualToString:@"coinNo"]) {//0 买, 1卖
        _coinNo = [change[NSKeyValueChangeNewKey] intValue];
        //获取委托单
        [self loadNewData];
        return;
    }
}
- (void)setMoneyType:(NSString *)moneyType {
    _moneyType = moneyType;
    self.headerView.unitLabel.text =  moneyType.intValue == 1 ? @"¥": @"€";
}
#pragma mark ---------------headerView按钮点击------------------

/**币子选择按钮点击 **/
- (void)didClickCoinNameButton {
    
    TJSelectCoinController *selectCoinController = [[TJSelectCoinController alloc] init];
//    [selectCoinController setSelectComplete:^(NSString * _Nonnull Unit, NSString * _Nonnull name) {
//        NSLog(@"Unit=%@ name=%@", Unit, name);// CNY USDT
//        self.coinUnit = Unit;
//        self.coinName = name;
//        TJGlobalFunc.globalFunc.OTCMainModel.coinNo = [name isEqualToString:@"BTC"] ? 1 : 2;
//        [self.headerView.coinNameButton setTitle:[NSString stringWithFormat:@"%@/%@", Unit, name] forState:UIControlStateNormal];
//        [self.headerView.coinNameButton setImagePosition:LXMImagePositionRight spacing:3];
//        
//        self.moneyType = [Unit isEqualToString:@"CNY"] ? @"1" : @"2";
//        NSInteger selectIndex = [name isEqualToString:@"BTC"] ? 0 : 1;
//        [self.headerView.categoryView selectItemAtIndex: selectIndex];
//        
//        [self setPriceValue];
//    }];
    [self presentViewController:selectCoinController animated:NO completion:nil];
}
/**订单按钮点击 **/
- (void)didClickOrderButton {
    [self.navigationController pushViewControllerWithName:@"TJOrderRecardListController" title:@"订单记录".localizedString animated:YES];
}
/**购买按钮点击 **/
- (void)didClickBuyButton {
    
    [self.view endEditing:YES];
    
    NSString *number = _headerView.numberTextField.text;
    NSLog(@"headerView.buyWayButton.isSelected = %d", _headerView.buyWayButton.isSelected);
    if (_headerView.buyWayButton.isSelected) {//按金额购买
        if (number.floatValue <= 0) {
            [TJHud showAutoHideMessage:_headerView.numberTextField.placeholder];
            return;
        }
        
    } else {
        if (number.floatValue < 100) {
            [TJHud showAutoHideMessage:_headerView.numberTextField.placeholder];
            return;
        }
    }
     //用户认证查询
    [self loadAuthData];
}
/**筛选按钮点击 **/
- (void)didClickScreeningButton {
    TJOrderListScreeningController *orderListScreeningController = [[TJOrderListScreeningController alloc] init];
//    [orderListScreeningController setSelectComplete:^(NSString * _Nonnull amountText, NSArray<TJOrderListScreeningModel *> * _Nonnull models) {
//        
//        if (amountText.floatValue > 100) {
//            self.money = amountText;
//        }
//        
//        TJOrderListScreeningModel *payTypeModel = models.firstObject;
//        TJOrderListScreeningModel *moneyTypeModel = models.lastObject;
//        
//        self.payType = payTypeModel.identifier;
//        self.moneyType = moneyTypeModel.identifier;
//        self.coinUnit = moneyTypeModel.text;
//        
//        
//        [self.headerView.coinNameButton setTitle:[NSString stringWithFormat:@"%@/%@", self.coinUnit, self.coinName] forState:UIControlStateNormal];
//        [self.headerView.coinNameButton setImagePosition:LXMImagePositionRight spacing:3];
//        NSInteger selectIndex = [self.coinName isEqualToString:@"BTC"] ? 0 : 1;
//        [self.headerView.categoryView selectItemAtIndex: selectIndex];
//          //获取委托单
//        [self loadNewData];
//    }];
    
    [self presentViewController:orderListScreeningController animated:NO completion:nil];
}

/**获取委托单 **/
- (void)loadNewData {
    
    NSMutableDictionary *parameters = @{
        //1,btc 2,usdt
        @"coinNo": @(_coinNo).stringValue,
        @"pageSize": @(50),
        @"moneyType": _moneyType,//1,cny 2,eur
        @"pageNum": @(_pageIndex),
        @"entrustType": @(!_selectType).stringValue,//0.买单1.卖单
    }.mutableCopy;
    
    if (_money.floatValue) {
        [parameters setObject:_money forKey:@"money"];
    }
    if (_payType.intValue) {
        [parameters setObject:_payType forKey:@"payType"];
    }
    
    TJLog(@"loadNewData%@", parameters);
    
    [TJNetworking.shareNetworking POST:@"entrust/query" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        self.displayEmpty = YES;
        
        NSMutableArray *dataArr = [TJOrderListModel mj_objectArrayWithKeyValuesArray:data[@"list"]];
        if (dataArr.count) {
            self.datas = dataArr;
        } else {
            [self.datas removeAllObjects];
        }
        [self.tableView reloadData];
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
    
}
//获取所有币种单价
- (void)loadCoinPriceData {
    
    [TJNetworking.shareNetworking POST:@"home/getUnitPrice" parameters:nil success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        self.priceDict = data;
        [self setPriceValue];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)setPriceValue {
    NSString *price = self.priceDict[self.coinUnit.lowercaseString][self.coinName];
    self.headerView.priceLabel.text = [NSString stringWithFormat:@"单价约%@%@/%@".localizedString, price,self.coinUnit, self.coinName];
    NSLog(@"price = %@", price);
}

//匹配币
- (void)loadMatchEntrustData {
    
    NSString *buyType = _headerView.buyWayButton.isSelected ? @"2" : @"1";// 1,金额,2数量
    //0.买单1.卖单
    NSString *entrustType = (_selectType == 0) ? @"1" : @"0";
    NSString *num = _headerView.numberTextField.text;
    NSString *moneyType = [_coinUnit isEqualToString:@"CNY"] ? @"1" : @"2";
    
    NSMutableDictionary *parameters = @{
        @"payType": _payType,
        @"coinNo": @(_coinNo).stringValue,
        @"moneyType": moneyType,
        @"buyType": buyType,
        @"entrustType": entrustType,
        @"token": TJUserInfo.readInfo.token
    }.mutableCopy;
    
    if (buyType.intValue == 1) {
        [parameters setObject:num forKey:@"money"];
    } else {
        [parameters setObject:num forKey:@"num"];
    }
    
    [self showloading];
    
    [TJNetworking.shareNetworking POST:@"entrust/matchEntrust" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        [self hiddenloading];
        
        if (![data isKindOfClass:NSDictionary.class] && data.allKeys.count == 0) {
            [TJHud showAutoHideMessage:responseObject[@"msg"]];
            return;
        }
        
        self.matchEntrustDict = data;
        TJLog(@"%@",data);
        
        TJConfirmOrderController *confirmOrderController = [[TJConfirmOrderController alloc] init];
        confirmOrderController.dict = data;
        [confirmOrderController setSelectComplete:^{
            
            TJInputPasswordControntroller *inputPasswordControntroller = [[TJInputPasswordControntroller alloc] init];
            [inputPasswordControntroller setSelectComplete:^(NSString * _Nonnull password) {
                [self createOrderWithPassword:password];
            }];
            
            [inputPasswordControntroller setForgetPasswordBlock:^{
                [self.navigationController pushViewControllerWithName:@"TJForgetPasswordController" title:@"" animated:YES];
            }];
            
            [self presentViewController:inputPasswordControntroller animated:YES completion:nil];
        }];
        
        [self presentViewController:confirmOrderController animated:YES completion:nil];
        
    } failure:^(NSError * _Nonnull error) {
        [self hiddenloading];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
}

#pragma mark -----------------tableViewdegegatel----------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TJOrderListCell *cell = [tableView dequeueReusableCellWithIdentifier:orderListCell forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.model = self.datas[indexPath.row];
    cell.delegate = self;
    return cell;
}
#pragma mark ---------------TJOrderListCellDelegate------------------
- (void)tapSellLabelWithCell:(TJOrderListCell *)cell {
    
    TJOrderListModel *listModel = cell.model;
    
    
    [self showloading];
    [TJNetworking.shareNetworking POST:@"user/isAuth" parameters:@{@"token": TJUserInfo.readInfo.token} success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        [self hiddenloading];
        self.authDict = data;
        if ([self.authDict[@"phone"] isEqualToString:@"1"] && [self.authDict[@"oneAuth"] isEqualToString:@"1"] && [self.authDict[@"twoAuth"] isEqualToString:@"1"]) {
            
            TJQuickTradingController *quickTradingController  = [[TJQuickTradingController alloc] init];
            quickTradingController.model = listModel;
            
            [quickTradingController setSelectComplete:^(NSString * _Nonnull numberText, NSString * _Nonnull buyType) {
                NSLog(@"setSelectComplete");
                
                TJSelectPayWayController *selectPayWayController = [[TJSelectPayWayController alloc] init];
                [selectPayWayController setSelectComplete:^(TJCellStyleModel * _Nonnull model) {
                    NSLog(@"--%@--%@", model.text, model.identification);
                    self.payType = model.identification;
                    if (listModel.entrustType.intValue == 0) {//卖
                        TJInputPasswordControntroller *inputPasswordControntroller = [[TJInputPasswordControntroller alloc] init];
                        [inputPasswordControntroller setSelectComplete:^(NSString * _Nonnull password) {
                            [self createOrderWithNumberText:numberText buyType:buyType listModel:listModel password:password];
                        }];
                        
                        
                        [inputPasswordControntroller setForgetPasswordBlock:^{
                            [self.navigationController pushViewControllerWithName:@"TJForgetPasswordController" title:@"" animated:YES];
                        }];
                        
                        [self presentViewController:inputPasswordControntroller animated:YES completion:nil];
                        
                    } else {//买
                        [self createOrderWithNumberText:numberText buyType:buyType listModel:listModel password:nil];
                    }
                    
                }];
                [self presentViewController:selectPayWayController animated:NO completion:nil];
                
            }];
            
            [self presentViewController:quickTradingController animated:YES completion:nil];
            
   
            
        } else {//未认证
            TJBuySellNeedAuthController *buySellNeedAuthController = [[TJBuySellNeedAuthController alloc] init];
//            buySellNeedAuthController.dict = data;
            buySellNeedAuthController.title = @"法币交易完成以下认证：".localizedString;
            [self presentViewController:buySellNeedAuthController animated:NO completion:nil];
        }
    } failure:^(NSError * _Nonnull error) {
        [self hiddenloading];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
 
}
 //用户认证查询
- (void)loadAuthData {
    [self showloading];
   
    [TJNetworking.shareNetworking POST:@"user/isAuth" parameters:@{@"token": TJUserInfo.readInfo.token} success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        [self hiddenloading];
        self.authDict = data;
        //1表示已认证，其他表示未认证
        if ([self.authDict[@"phone"] isEqualToString:@"1"] && [self.authDict[@"oneAuth"] isEqualToString:@"1"] && [self.authDict[@"twoAuth"] isEqualToString:@"1"]) {
            
            TJSelectPayWayController *selectPayWayController = [[TJSelectPayWayController alloc] init];
            [selectPayWayController setSelectComplete:^(TJCellStyleModel * _Nonnull model) {
                NSLog(@"--%@--%@", model.text, model.identification);
                //1,微信，2，支付宝，3，银行卡
                self.payType = model.identification;
                [self loadMatchEntrustData];
            }];
            [self presentViewController:selectPayWayController animated:NO completion:nil];
        } else {//未认证
            TJBuySellNeedAuthController *buySellNeedAuthController = [[TJBuySellNeedAuthController alloc] init];
//            buySellNeedAuthController.dict = data;
            buySellNeedAuthController.title = @"法币交易完成以下认证：".localizedString;
            [self presentViewController:buySellNeedAuthController animated:NO completion:nil];
        }
    } failure:^(NSError * _Nonnull error) {
        [self hiddenloading];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
}

/**创建订单 **/
- (void)createOrderWithNumberText:(NSString *)numberText buyType:(NSString *)buyType listModel:(TJOrderListModel *)listModel password:(NSString *)password  {
    
    NSString *money = buyType.intValue == 1 ? numberText : [NSString stringWithFormat:@"%f", numberText.floatValue * listModel.entrustPrice.floatValue];
    money = [Tools CNYString:money];
    
    NSMutableDictionary *parameters = @{
        @"entrustId":listModel.entrustId,//委托id
        @"money": money,//金额
        @"token": TJUserInfo.readInfo.token,
        @"payType": self.payType,//1,微信，2，支付宝，3，银行卡
    }.mutableCopy;
    
    if (password) {//资金密码
        [parameters setValue:password.qmui_md5 forKey:@"password"];
    }
    
    [TJNetworking.shareNetworking POST:@"order/createBuyOrder" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        TJOrderDetailControntroller *orderDetailControntroller = [[TJOrderDetailControntroller alloc] init];
        orderDetailControntroller.orderId = data[@"orderId"];
        [self.navigationController pushViewController:orderDetailControntroller animated:YES];
        
    } failure:^(NSError * _Nonnull error) {
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
}

/**创建订单 **/
- (void)createOrderWithPassword:(NSString *)password {
    
    NSMutableDictionary *parameters = @{
        @"entrustId": _matchEntrustDict[@"entrustId"],
        @"password": password.qmui_md5,
        @"money": _matchEntrustDict[@"money"],
        @"token": TJUserInfo.readInfo.token,
        @"payType": _payType,
    }.mutableCopy;
    
    
    [TJNetworking.shareNetworking POST:@"order/createBuyOrder" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        TJOrderDetailControntroller *orderDetailControntroller = [[TJOrderDetailControntroller alloc] init];
        orderDetailControntroller.orderId = data[@"orderId"];
        [self.navigationController pushViewController:orderDetailControntroller animated:YES];
        
    } failure:^(NSError * _Nonnull error) {
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
}

- (void)dealloc {
//    [TJGlobalFunc.globalFunc.OTCMainModel removeObserver:self forKeyPath:@"coinNo"];
    
}
@end
